package org.itboys.shop.service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.product.entity.ProductMinPrice;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.shop.entity.ShopSeller;
import org.mongodb.morphia.geo.GeoJson;
import org.mongodb.morphia.geo.Point;
import org.mongodb.morphia.mapping.Mapper;
import org.mongodb.morphia.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import javafx.geometry.Point2D;

/**
 * 商家
 * @author weisky
 *
 */
@Service
public class ShopSellerService extends BaseService<ShopSeller, Long>{

    private static final long serialVersionUID = 1L;
    @Resource(name = "sellerDS")
    private MongoDataSource ds;

    @Autowired
    private ResourceHolder resourceHolder;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<ShopSeller> getEntityClass() {
        return ShopSeller.class;
    }

    /**
     * 根据商店名称模糊查询列表
     * @return
     */
    public List<ShopSeller> getShopListListByName(String sellerName) {
        return ds.createQuery(getEntityClass()).filter("name", AceUtils.getPattern(sellerName))
                .filter("isDeleted", SellerConstants.TYPE_ZERO).asList();
    }

    public List<ShopSeller> getShopListByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return ds.createQuery(getEntityClass()).field(Mapper.ID_KEY).in(ids).asList();
    }

    /**
     * 保存或修改
     * @param seller
     * @param logos:商家logo
     * @param mainImgs:商家主图
     * @return
     */
    public boolean insert(ShopSeller seller, MultipartFile logos, MultipartFile mainImgs,
                          MultipartFile personCarImgs, MultipartFile businessLicenseImgs,
                          MultipartFile foodLicenseImgs){
        try{
            String logo = null;
            String mainImg = null;
            String personCarImg = null;
            String businessLicenseImg = null;
            String foodLicenseImg = null;

            if(logos != null && !logos.isEmpty()){
                logo = FileUtils.saveFile(logos.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        logos.getOriginalFilename(), logos.getContentType());
                seller.setLogo(logo);
            }
            if(mainImgs != null && !mainImgs.isEmpty()){
                mainImg = FileUtils.saveFile(mainImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        mainImgs.getOriginalFilename(), mainImgs.getContentType());
                seller.setMainImg(mainImg);
            }
            if(personCarImgs != null && !personCarImgs.isEmpty()){
                personCarImg = FileUtils.saveFile(personCarImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        personCarImgs.getOriginalFilename(), personCarImgs.getContentType());
                seller.setPersonCarImg(personCarImg);
            }
            if(businessLicenseImgs != null && !businessLicenseImgs.isEmpty()){
                businessLicenseImg = FileUtils.saveFile(businessLicenseImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        businessLicenseImgs.getOriginalFilename(), businessLicenseImgs.getContentType());
                seller.setBusinessLicenseImg(businessLicenseImg);
            }
            if(foodLicenseImgs != null && !foodLicenseImgs.isEmpty()){
                foodLicenseImg = FileUtils.saveFile(foodLicenseImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        foodLicenseImgs.getOriginalFilename(), foodLicenseImgs.getContentType());
                seller.setFoodLicenseImg(foodLicenseImg);
            }

            if(seller.getId() != 0){//修改
                ShopSeller seller2 = getById(seller.getId());
                //设置商家的logo
                if(StringUtils.isBlank(logo)){
                    seller.setLogo(seller2.getLogo());
                }
                //设置商家的主图
                if(StringUtils.isBlank(mainImg)){
                    seller.setMainImg(seller2.getMainImg());
                }
                if(StringUtils.isBlank(personCarImg)){
                    seller.setPersonCarImg(seller2.getPersonCarImg());
                }
                if(StringUtils.isBlank(businessLicenseImg)){
                    seller.setBusinessLicenseImg(seller2.getBusinessLicenseImg());
                }
                if(StringUtils.isBlank(foodLicenseImg)){
                    seller.setFoodLicenseImg(seller2.getFoodLicenseImg());
                }
                update(seller);
                logger.info("修改店铺信息成功：Seller=" + JSON.toJSONString(seller));
            }else{//新增
                save(seller);
                logger.info("新增店铺信息成功：Seller=" + JSON.toJSONString(seller));
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerService.insert error", e);
            return false;
        }
    }

    /**
     * 修改商家的状态
     * @param sellerId
     * @param state
     * @return
     */
    public boolean updateState(Long sellerId, int state){
        try{
            update(sellerId, "state", state);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerService.updateState error", e);
            return false;
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public boolean dele(Long id){
        try{
            delete(id);
            logger.info("删除店铺成功：Seller.id=" + id + ", 删除时间 = " + new Date());
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerService.dele error", e);
            return false;
        }
    }

    //获取某店铺下最低价格
    public int getMinPrice(long sellerId) {
        ProductMinPrice minPrice = getMongoDataSource().createQuery(ProductMinPrice.class)
                .field("sellerId").equal(sellerId).get();
        return minPrice == null ? 0 : minPrice.getMinPrice();
    }
    public List<ShopSeller> getNear(Long sellerId,int type){
    	ShopSeller seller=getById(sellerId);
    	Double longitude=Double.valueOf(seller.getCoordinate()[0]);
    	Double latitude=Double.valueOf(seller.getCoordinate()[1]);
    	Point point=GeoJson.point(latitude,longitude );
    	Query<ShopSeller>query=getMongoDataSource().createQuery(getEntityClass()).field("coordinate").near(point).filter("centerId", seller.getCenterId()).filter("shopType", type).limit(4);
    	return query.asList();
    }
}
